package com.client.koshercook.client;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.event.dom.client.KeyUpHandler;
import com.google.gwt.i18n.client.HasDirection.Direction;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.HasAlignment;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.PushButton;
import com.google.gwt.user.client.ui.TextArea;
import com.google.gwt.user.client.ui.VerticalPanel;

public class CommentBox extends Composite{

	private PushButton open = new PushButton("הוסף תגובה");
	private Button ok = new Button("אישור");
	private Button cancel = new Button("ביטול");
	private DialogBox dBox = new DialogBox();
	private VerticalPanel Vpanel = new VerticalPanel();
	private HorizontalPanel HpanelDown = new HorizontalPanel();
	private TextArea commentTextArea = new TextArea();
	
	private String link; 
	
	/*get a comment from the user, update the recipe and user data base and the GUI comment list*/
	public CommentBox(){
		
		commentTextArea.setDirection(Direction.RTL);
		commentTextArea.setCharacterWidth(80);
		commentTextArea.setVisibleLines(5);
		
		commentTextArea.addKeyUpHandler(new KeyUpHandler(){
			public void onKeyUp(KeyUpEvent event) {
				if (event.getNativeKeyCode() == KeyCodes.KEY_ESCAPE) {
					dBox.hide();
					commentTextArea.setFocus(false);
				}
			}
		});
		
		open.addClickHandler(new ClickHandler(){
			public void onClick(ClickEvent event) {
				if(!Client.model.isConnected()){
					Client.model.setInfoTextAndPO("עליך להיות מחובר בכדי להוסיף תגובה");
				}else{
					dBox.center();
					commentTextArea.setFocus(true);
				}
			}
		});

		ok.addClickHandler(new ClickHandler(){
			public void onClick(ClickEvent event) {
				String comment = commentTextArea.getText();
				if(comment.equals("")){
					return;
				}
				Client.model.addComment(link, comment);
				clear();
			}
		});

		cancel.addClickHandler(new ClickHandler(){
			public void onClick(ClickEvent event) {
				clear();
			}
		});
		Vpanel.setHorizontalAlignment(HasAlignment.ALIGN_RIGHT);
		Vpanel.add(commentTextArea);
		Vpanel.add(HpanelDown);
		HpanelDown.add(cancel);
		HpanelDown.add(ok);
		HpanelDown.setSpacing(3);
		dBox.add(Vpanel);
		dBox.setText("הוסף תגובה");
		clear();

		initWidget(open);
	}
	
	/** clear text fields and hide the dialog box */
	private void clear(){
		dBox.hide();
		commentTextArea.setText("");
	}
	
	public void setLink(String link){
		this.link = link;
	}
	
	public void disable(){
		open.setEnabled(false);
	}
	
	public void enable(){
		open.setEnabled(true);
	}
}
